import sys
import os
import json
import threading
from functools import partial  # 1. 导入 partial
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QListWidget, QListWidgetItem, QLabel, QMessageBox
)
from PySide6.QtCore import Qt, QSize


class ConfigScanWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("配置文件扫描工具")
        self.setGeometry(100, 100, 800, 600)

        # 创建中央控件和主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QHBoxLayout(central_widget)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # 左侧布局
        left_layout = QVBoxLayout()
        
        # 扫描按钮
        self.scan_button = QPushButton("扫描配置文件")
        self.scan_button.setFixedSize(180, 40)
        self.scan_button.clicked.connect(self.scan_config_files)
        
        left_layout.addWidget(self.scan_button)
        left_layout.addStretch()

        # 右侧布局
        right_layout = QVBoxLayout()
        
        # 列表控件
        self.config_list = QListWidget()
        self.config_list.setStyleSheet("""
            QListWidget {
                border: 1px solid #cccccc;
                border-radius: 6px;
                padding: 5px;
                background-color: #f9f9f9;
            }
            QListWidget::item {
                height: 40px;
                border-bottom: 1px solid #eeeeee;
            }
            QListWidget::item:selected {
                background-color: #e0e0e0;
            }
        """)

        right_layout.addWidget(self.config_list)

        # 添加到主布局
        main_layout.addLayout(left_layout, 1)
        main_layout.addLayout(right_layout, 3)

        # 初始化配置文件夹路径
        self.config_dir = os.path.join(os.getcwd(), "Base64Config")

    def scan_config_files(self):
        """扫描配置文件夹中的JSON文件"""
        # 清空列表
        self.config_list.clear()

        # 检查配置文件夹是否存在
        if not os.path.exists(self.config_dir):
            QMessageBox.warning(self, "警告", f"配置文件夹不存在：{self.config_dir}")
            return

        # 检查是否是目录
        if not os.path.isdir(self.config_dir):
            QMessageBox.warning(self, "警告", f"{self.config_dir} 不是一个目录")
            return

        # 扫描JSON文件
        json_files = []
        for filename in os.listdir(self.config_dir):
            if filename.endswith(".json"):
                json_files.append(filename)

        if not json_files:
            QMessageBox.information(self, "信息", "未找到任何JSON配置文件")
            return

        # 添加到列表
        for filename in json_files:
            self.add_config_item(filename)

        QMessageBox.information(self, "扫描完成", f"共找到 {len(json_files)} 个配置文件")

    def add_config_item(self, filename):
        """添加配置项到列表（包含三个平台按钮）"""
        # 创建列表项
        item = QListWidgetItem(self.config_list)
        item.setSizeHint(QSize(0, 50))

        # 创建自定义控件
        widget = QWidget()
        layout = QHBoxLayout(widget)
        layout.setContentsMargins(10, 5, 10, 5)
        layout.setSpacing(10)

        # 文件名标签
        label = QLabel(filename)
        label.setStyleSheet("font-size: 14px;")
        
        # 按钮容器
        button_layout = QHBoxLayout()
        button_layout.setSpacing(5)

        # 创建三个平台按钮
        platforms = ["拼多多", "抖店", "淘宝"]
        for platform in platforms:
            button = QPushButton(platform)
            button.setFixedSize(80, 30)
            button.setStyleSheet("""
                QPushButton {
                    background-color: #4a90e2;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #5ba0f2;
                }
                QPushButton:pressed {
                    background-color: #3a80d2;
                }
            """)
            
            # --- 这里是关键的修改 ---
            # 使用 functools.partial 来绑定参数
            # partial会创建一个新函数，当这个新函数被调用时，会把预先绑定的参数和新传入的参数一起传给原始函数
            # self.on_button_click 是原始函数
            # filename 和 platform 是我们要预先绑定的参数
            button.clicked.connect(partial(self.on_button_click, filename, platform))
            
            button_layout.addWidget(button)

        # 添加到布局
        layout.addWidget(label, 1)
        layout.addLayout(button_layout)

        # 设置列表项的widget
        self.config_list.setItemWidget(item, widget)

    def on_button_click(self, filename, button_name):
        """处理所有按钮点击事件"""
        # 拼接完整的JSON文件路径
        json_path = os.path.join(self.config_dir, filename)
        
        # 打印文件路径和按钮名称
        print(f"配置文件路径：{json_path}")
        print(f"点击的按钮：{button_name}")
        print("-" * 50)  # 分隔线，方便查看
        
        
        if button_name == "拼多多":
            from SimpleWrapper.Extension.SeleniumExtension.CategoryAbstraction.Selenium平台多多童装 import PinDuoDuo_TongZhuang
            threading.Thread(target=PinDuoDuo_TongZhuang().FastStart, args=(json_path,)).start()
        elif button_name == "抖店":
            from SimpleWrapper.Extension.SeleniumExtension.CategoryAbstraction.Selenium平台抖店童装 import DouDian_TongZhuang
            threading.Thread(target=DouDian_TongZhuang().FastStart, args=(json_path,)).start()
        elif button_name == "淘宝":
            from SimpleWrapper.Extension.SeleniumExtension.CategoryAbstraction.Selenium平台淘宝童装 import TaoBao_TongZhuang
            threading.Thread(target=TaoBao_TongZhuang().FastStart, args=(json_path,)).start()
        


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ConfigScanWindow()
    window.show()
    sys.exit(app.exec())